/**
 * JAVACC DEMO 1.0
 */
package com.apache.portal.contorller;

import com.apache.api.vo.ResultEntity;
import com.apache.api.vo.ResultMsg;
import com.apache.cache.service.impl.LoadCacheFactory;
import com.apache.cache.util.Validator;
import com.apache.client.UctCoreClient;
import com.apache.portal.common.PortalPlugin;
import com.apache.portal.common.annotion.BeanFactory;
import com.apache.portal.common.restfull.RequestMapping;
import com.apache.portal.common.restfull.ResultFullAnntation;
import com.apache.portal.common.restfull.SupperAction;
import com.apache.portal.common.util.PortalPubFactory;
import com.apache.portal.common.util.PortalUtil;
import com.apache.portal.common.websocket.WebsocketClient;
import com.apache.portal.thread.CreateParamManagerInfoJob;
import com.apache.security.util.SecurityHttpServletRequest;
import com.apache.security.util.SecurityHttpServletResponse;
import com.apache.tools.ConfigUtil;
import com.apache.tools.StrUtil;
import com.apache.uct.common.LoginUser;
import com.apache.uct.common.ToolsUtil;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * description:  获取信息列表Action
 *
 * @author Hou Dayu 创建时间：2016-4-13
 */
@SuppressWarnings("serial")
@ResultFullAnntation(name = "sendPageAction", urlPatterns = { "/sendPage/*", "/sendPage/*/*",
        "/sendPage/*/*/*", "/sendPage/*/*/*/*", "/sendPage/*/*/*/*/*" })
public class SendPageAction extends SupperAction {

    private PortalPlugin dictPlugin;

    private PortalPlugin infoPlugin;

    private String whiteUrl="/web/user,/admin,";
    //定自义登录页面
    private String customLogin = "";

    public void init() {
        dictPlugin = (PortalPlugin) BeanFactory.getInstance().getBeans("dict");
        infoPlugin = (PortalPlugin) BeanFactory.getInstance().getBeans("info");
    }

    /**
     * TODO 简单描述该方法的实现功能（可选）.
     */
    protected void doInvoke(HttpServletRequest request, HttpServletResponse response,
            String methodType) throws Exception {
        HttpServletRequest req = request;
        HttpServletResponse res = response;
        if ("true".equalsIgnoreCase(
                ToolsUtil.getInstance().getValueByKey("is_open_security_filter"))) {//是否开启安全过滤
            req = new SecurityHttpServletRequest(request);
            res = new SecurityHttpServletResponse(response);
        }
        if ("get".equalsIgnoreCase(methodType)) {
            Method method = doInvoke(this.getClass(), req, res, methodType, "");
            if (null == method) {
                sendPage(req, res);
            } else {
                Object obj = method.invoke(this, req, res);
                if (!ToolsUtil.isEmpty(obj)) {
                    JSONObject array = JSONObject.fromObject(obj);
                    this.outputJson(array.toString(), res, req.getParameter("callback"));
                }
            }
        } else {
            gotoErrorPage(request, response, "请求的Action地址未定义");
        }
    }

    /**
     * description:  获取信息列表方法(ajax)
     * sendPage/~/web/user/和sendPage/~/admin
     */
    protected void sendPage(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {
        String str1 = String.valueOf(request.getAttribute("PathAttr0"));
        String str2 = String.valueOf(request.getAttribute("PathAttr1"));
        String str3 = String.valueOf(request.getAttribute("PathAttr2"));
        String str4 = String.valueOf(request.getAttribute("PathAttr3"));
        String str5 = String.valueOf(request.getAttribute("PathAttr4"));
        ////以下权限验证，只有登录的才能访问
        String str = whiteUrl+UctCoreClient.getConf_Map().get("noright_url");
        String[] wus = str.split(",");
        boolean mark = true;
        for (int i = 0; i < wus.length; i++) {
            String wuStr = wus[i];
            if (ToolsUtil.isNotNull(wuStr) && ((wuStr.indexOf("/"+str2)!=-1 && "admin".equals(str2)) || wuStr.indexOf("/"+str2+"/"+str3)!=-1)) {
                LoginUser loginUser = PortalUtil.getInstance().getLoginUser(request);
                //存在需要登录才能访问的地址时，如果loginuser为空则跳到登录页面
                if (ToolsUtil.isEmpty(loginUser)) {
                    mark = false;
                    break;
                }
            }
        }
        if(!mark){//没登录跳到登录页面
            gotoLogin(request,response);
            return ;
        }

        String pgeUrl = "/WEB-INF/pages/";
        if (StrUtil.isNull(str2)) {
            pgeUrl += str1 + ".jsp";
        } else if (StrUtil.isNull(str3)) {
            pgeUrl += str1 + "/" + str2 + ".jsp";
        } else if (StrUtil.isNull(str4)) {
            pgeUrl += str1 + "/" + str2 + "/" + str3 + ".jsp";
        } else if (StrUtil.isNull(str5)) {
            pgeUrl += str1 + "/" + str2 + "/" + str3 + "/" + str4 + ".jsp";
        } else if (StrUtil.isNotNull(str5)) {
            pgeUrl += str1 + "/" + str2 + "/" + str3 + "/" + str4 + "/" + str5 + ".jsp";
        }
        Map<String, Object> defMap = super.getDefaultDataMap(request);
        if(!defMap.isEmpty() && defMap.containsKey("config")){
            request.setAttribute("config",defMap.get("config"));
        }
        String params = StrUtil.doNull(request.getQueryString(), "");
        if (StrUtil.isNotNull(params))
            pgeUrl += "?" + params;
        request.getRequestDispatcher(pgeUrl).forward(request, response);
    }

    /**
     * description: 生成表单防重复提交令牌
     */
    @RequestMapping(value = "token", method = "get")
    public void token(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String uuid = setToken(request);
        this.outputJson(uuid, response, request.getParameter("callback"));
    }

    /**
     * description: 生成表单防重复提交令牌
     */
    @RequestMapping(value = "sendMsg", method = "get")
    public ResultMsg sendMsg(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        String value = request.getParameter("message");
        if (value.equals(new String(value.getBytes("iso8859-1"), "iso8859-1"))) {
            value = new String(value.getBytes("iso8859-1"), "utf-8");
        }
        String userEname = request.getParameter("userEname");
        String sysPass = "/uct?userEname=" + userEname + "&sysPass=" + ConfigUtil.getInstance()
                .getValueByKey("sysEname");
        //        PubWebSorcketClient c = PortalUtil.getWebsocketCLient("uctsocket_url", sysPass);
        //        if (!Validator.isEmpty(c)) {
        //            c.send(value);
        //        }
        WebsocketClient.getInstance().sendMessage("uctsocket_url", "", sysPass, value);

        return new ResultMsg("T", "消息推送成功");
    }

    /**
     * description: 生成paramManager信息缓存
     */
    @RequestMapping(value = "loadCache", method = "get")
    public void loadCache(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        CreateParamManagerInfoJob.getInstance().initParamManagerInfo();
        ResultMsg msg = new ResultMsg("T", "操作成功");
        JSONObject array = JSONObject.fromObject(msg);
        this.outputJson(array.toString(), response, request.getParameter("callback"));
    }

    /**
     * description: 生成表单防重复提交令牌
     */
    @RequestMapping(value = "viewCache", method = "get")
    public Object viewCache(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        String spaeName = StrUtil.doNull(request.getParameter("spaeName"), "");
        String code = request.getParameter("code");
        Map<String, Object> data = new HashMap<String, Object>();
        if (StrUtil.isNull(code)) {
            data.put("flag", "F");
            data.put("msg", "缺少缓存参数");
        }
        Object obj = LoadCacheFactory.getInstance().getCacheManager(spaeName)
                .getCacheObjectByKey(code);
        data.put("flag", "T");
        data.put("msg", String.valueOf(obj));
        return data;
    }

    /**
     * description: 生成paramManager信息缓存
     */
    @RequestMapping(value = "initCache", method = "get")
    public Object initCache(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        Map<String, String> params = this.getParameterMap(request);
        params.put("doCode", "initCache");
        ResultEntity entity = (ResultEntity) dictPlugin.doInvoke(request, response, params);
        Map<String, Object> data = new HashMap<String, Object>();
        ResultEntity entity2 = (ResultEntity) infoPlugin.doInvoke(request, response, params);
        data.put("flag", "T");
        data.put("msg", "缓存刷新成功");
        return data;
    }

    private String setToken(HttpServletRequest request) {
        if (Validator.isNotNull(request.getParameter("token"))) {
            HttpSession session = request.getSession(true);
            String uuid = UUID.randomUUID().toString();
            if (null != session)
                session.setAttribute("formToken", uuid);
            return uuid;
        }
        return "";
    }

    /**
     * description:  跳到登录页面
     */
    private void gotoLogin(HttpServletRequest request,HttpServletResponse response)
            throws IOException {
        //自定义登录页面
        String customLogin = ToolsUtil.getInstance().getLocalByKey("config.properties","custom_login");
        String redUrl = request.getContextPath() + StrUtil.doNull(customLogin, "/");
        log.info("not logged! redirects to custom login page -> "+redUrl);
        response.sendRedirect(redUrl);
    }
}
